import { useState } from 'react';
import { notification } from 'antd';
import { utils } from 'vv-frontend-components';
import request from '@/utils/request';
import { departmentGetone } from '@/services/Organization/staffmanage';

const { deepTrim } = utils;
export const useInit = () => {
    const [formData, setFormData] = useState({});
    const [loading, setLoading] = useState(false);
    const [spinning, setSpinning] = useState(false);
    // 公司id 切换公司做表单项联动操作时需要
    const [observableId, setObservableId] = useState(null);
    // 部门主管的name值
    const [departmentManager, setDepartmentManager] = useState(null);
    return {
        formData,
        setFormData,
        observableId,
        loading,
        setLoading,
        setObservableId,
        spinning,
        setSpinning,
        departmentManager,
        setDepartmentManager
    };
};
/**
 * 新增||编辑部门 提交方法
 */
export const handleSubmit = async props => {
    const {
        treeNode: { id },
        setLoading,
        value,
        departmentManager,
        isEditDepartment,
        callback
    } = props;
    const url = '/api/oa/v1/department/saveorupdate';
    setLoading(true);
    const result = await request(url, {
        method: 'POST',
        data: deepTrim({
            ...value,
            departmentManager: value.departmentManagerId === undefined ? '' : departmentManager, // 如果部门主管没值，清除字段
            id: isEditDepartment ? id : null,
            postIds: value.postIds.filter(item => item.value).map(item => item.value)
        })
    });
    setLoading(false);
    if (result && result.code === 10000) {
        callback();
    } else {
        notification.error({
            message: `请求错误 ${result.msg}`
        });
    }
};
/**
 * 查看部门详情
 * @param {string} departmentId
 */
export const getFormData = async props => {
    const { treeNode, setSpinning } = props;
    const { id } = treeNode;
    setSpinning(true);
    const res = await departmentGetone({ departmentId: id });
    setSpinning(false);
    if (res.code === 10000) {
        return res.data;
    }
    return {};
};
